﻿<%@ WebHandler Language="C#" Class="UploadTransaksiHandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using KPIReport.Library.DomainObject.Administration;
using KPIReport.Library.DataAccess.Administration;
using KPIReport.Library.DomainObject.Administration.Catalog;
using KPIReport.Library.DataAccess.Administration.Catalog;

using KPIReport.Web.Support;
using Newtonsoft.Json.Linq;
using Excel;
using System.IO;
using System.Data;

public class UploadTransaksiHandler : KPIReport.Web.BaseHandler
{

    private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["KpiReportConn"].ConnectionString);
    private transaksihdrRepo transaksihdrDal = new transaksihdrRepo(ConfigurationManager.ConnectionStrings["KpiReportConn"].ConnectionString);
    private transaksidtlRepo transaksidtlDal = new transaksidtlRepo(ConfigurationManager.ConnectionStrings["KpiReportConn"].ConnectionString);
    private transaksiReturdtlRepo transaksiReturdtlDal = new transaksiReturdtlRepo(ConfigurationManager.ConnectionStrings["KpiReportConn"].ConnectionString);
    private transaksiDNdtlRepo transaksiDNdtlDal = new transaksiDNdtlRepo(ConfigurationManager.ConnectionStrings["KpiReportConn"].ConnectionString);
   

    public override void ProcessRequest(HttpContext context)
    {
        string MethodName = string.Empty;
        base.ProcessRequest(context);

        MethodName = context.Request.Params["method"];


        switch (MethodName.Trim())
        {
            case ("uploadInvoiceHeader"):
                context.Response.Write(UploadInvoiceHeader(context));
                break;
            case ("uploadInvoiceDetail"):
                context.Response.Write(UploadInvoiceDetail(context));
                break;
            case ("uploadCNDetail"):
                context.Response.Write(UploadCNDetail(context));
                break;
            case ("uploadDNDetail"):
                context.Response.Write(UploadDNDetail(context));
                break;
            default:
                // do nothing
                break;
        }



    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private string UploadInvoiceHeader(HttpContext context)
    {
        JSONHelper helper = new JSONHelper();
         string FileName = string.Empty;
        try
        {

            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;

                var file = context.Request.Files[0];
               
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = hpf.FileName.Split(new char[] { '\\' });
                    FileName = files[files.Length - 1];
                }
                else
                {
                    FileName = hpf.FileName;
                }

                byte[] datas = new byte[hpf.ContentLength];
                hpf.InputStream.Position = 0;
                hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                string path = context.Server.MapPath("~/Upload/Transaksi/InvoiceHeader/");
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);

                
                if (System.IO.File.Exists(path+FileName))
                    System.IO.File.Delete(path + FileName);

                hpf.SaveAs(path + FileName);

                hpf.InputStream.Close();
                hpf.InputStream.Dispose();

            }

            DataTable dt = CSVReader.GetDataTabletFromCSVFile(context.Server.MapPath(@"~/Upload/Transaksi/InvoiceHeader/") + FileName);

            List<transaksihdr> listHdr = new List<transaksihdr>();
            transaksihdr objHdr = new transaksihdr();

            foreach (DataRow dr in dt.Rows)
            {
                objHdr = new transaksihdr();
                objHdr.Salesman_Code = dr[0].ToString().Trim();
                objHdr.Salesman_Name = dr[1].ToString().Trim();
                objHdr.Customer_Code = dr[2].ToString().Trim();
                objHdr.Customer_Name = dr[3].ToString().Trim();
                objHdr.Customer_Type = dr[4].ToString().Trim();
                objHdr.Invoice_Number = dr[5].ToString().Trim();
                objHdr.Sales_Order_Number = dr[6].ToString().Trim();
                objHdr.Warehouse_Code = dr[7].ToString().Trim();
                objHdr.Status = dr[8].ToString().Trim();
                objHdr.Invoice_Date = dr[9].ToString().Trim()==""?Convert.ToDateTime("1900-01-01"):Helper.FormatDate(dr[9].ToString().Trim(),Helper.Culture.English);
                objHdr.Due_Date = dr[10].ToString().Trim() == "" ? Convert.ToDateTime("1900-01-01") : Helper.FormatDate(dr[10].ToString().Trim(), Helper.Culture.English);
                objHdr.Customer_Area_Code = dr[11].ToString().Trim();
                objHdr.Total_Amount = dr[12].ToString().Trim()==""?0:Convert.ToDouble(dr[12].ToString().Trim());
                objHdr.Customer_Discount_Percentage = dr[13].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[13].ToString().Trim());
                objHdr.Customer_Discount_Amount = dr[14].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[14].ToString().Trim());
                objHdr.Total_Amount_after_Customer_Discount = dr[15].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[15].ToString().Trim());
                objHdr.Tax_Amount= dr[16].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[16].ToString().Trim());
                objHdr.Total_Net_Amount = dr[17].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[17].ToString().Trim());
                objHdr.Remark = dr[18].ToString().Trim();
                objHdr.Created_By = dr[19].ToString().Trim();
                listHdr.Add(objHdr);
            }

            transaksihdrDal.SaveUpload(listHdr);
            helper.Message = "Data berhasil di Upload !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }
        finally
        {
            recLog log = new recLog();
            log.LogEvent = "Upload Invoice Header";
            log.LogMessage = helper.Message;
            log.LogSource = "UploadTransaksiHandler.ashx";
            log.CreatedBy = base.UserLoggedIn;
            log.CreatedDate = DateTime.Now;
            logDal.Save(log);

        }

        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

    }

    private string UploadInvoiceDetail(HttpContext context)
    {
        JSONHelper helper = new JSONHelper();
        string FileName = string.Empty;
        try
        {

            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;

                var file = context.Request.Files[0];

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = hpf.FileName.Split(new char[] { '\\' });
                    FileName = files[files.Length - 1];
                }
                else
                {
                    FileName = hpf.FileName;
                }

                byte[] datas = new byte[hpf.ContentLength];
                hpf.InputStream.Position = 0;
                hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                string path = context.Server.MapPath("~/Upload/Transaksi/InvoiceDetail/");
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);

                
                if (System.IO.File.Exists(path + FileName))
                    System.IO.File.Delete(path + FileName);

                hpf.SaveAs(path + FileName);

                hpf.InputStream.Close();
                hpf.InputStream.Dispose();

            }



            DataTable dt = CSVReader.GetDataTabletFromCSVFile(context.Server.MapPath(@"~/Upload/Transaksi/InvoiceDetail/") + FileName);

            List<transaksidtl> listDtl = new List<transaksidtl>();
            transaksidtl objDtl = new transaksidtl();

            foreach (DataRow dr in dt.Rows)
            {
                objDtl = new transaksidtl();
                objDtl.Salesman_Code = dr[0].ToString().Trim();
                objDtl.Invoice_Number = dr[1].ToString().Trim();
                objDtl.Invoice_Date = dr[2].ToString().Trim() == "" ? Convert.ToDateTime("1900-01-01") : Helper.FormatDate(dr[2].ToString().Trim(), Helper.Culture.English);
                objDtl.Customer_Code = dr[3].ToString().Trim();
                objDtl.Product_Code = dr[4].ToString().Trim();
                objDtl.Product_Description = dr[5].ToString().Trim();
                objDtl.Product_Index = dr[6].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[6].ToString().Trim());
                objDtl.Selling_Type = dr[7].ToString().Trim();
                objDtl.Product_Quantity = dr[8].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[8].ToString().Trim()); ;
                objDtl.UOM = dr[9].ToString().Trim();
                objDtl.Default_UOM = dr[10].ToString().Trim();
                objDtl.Product_List_Price = dr[11].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[11].ToString().Trim());
                objDtl.UOM_List_Price = dr[12].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[12].ToString().Trim());
                objDtl.Gross_Amount = dr[13].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[13].ToString().Trim());
                objDtl.Product_Discount = dr[14].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[14].ToString().Trim());
                objDtl.Promo_Discount = dr[15].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[15].ToString().Trim());
                objDtl.Sales_Discount = dr[16].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[16].ToString().Trim());
                objDtl.Amount = dr[17].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[17].ToString().Trim());
                objDtl.Tax_Amount = dr[18].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[18].ToString().Trim());
                objDtl.Amount_After_Tax = dr[19].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[19].ToString().Trim());
                objDtl.Customer_Discount_Amount = dr[20].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[20].ToString().Trim());
                
                listDtl.Add(objDtl);
            }

            transaksidtlDal.SaveUpload(listDtl);

            helper.Message = "Data berhasil di Upload !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }
        finally
        {
            recLog log = new recLog();
            log.LogEvent = "Upload Invoice Detail";
            log.LogMessage = helper.Message;
            log.LogSource = "UploadTransaksiHandler.ashx";
            log.CreatedBy = base.UserLoggedIn;
            log.CreatedDate = DateTime.Now;
            logDal.Save(log);

        }

        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

    }

    private string UploadCNDetail(HttpContext context)
    {
        JSONHelper helper = new JSONHelper();
        string FileName = string.Empty;
        try
        {

            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;

                var file = context.Request.Files[0];

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = hpf.FileName.Split(new char[] { '\\' });
                    FileName = files[files.Length - 1];
                }
                else
                {
                    FileName = hpf.FileName;
                }

                byte[] datas = new byte[hpf.ContentLength];
                hpf.InputStream.Position = 0;
                hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                string path = context.Server.MapPath("~/Upload/Transaksi/CNDetail/");
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);

               
                if (System.IO.File.Exists(path + FileName))
                    System.IO.File.Delete(path + FileName);

                hpf.SaveAs(path + FileName);

                hpf.InputStream.Close();
                hpf.InputStream.Dispose();

            }

            DataTable dt = CSVReader.GetDataTabletFromCSVFile(context.Server.MapPath(@"~/Upload/Transaksi/CNDetail/") + FileName);

            List<transaksiReturdtl> listDtl = new List<transaksiReturdtl>();
            transaksiReturdtl objDtl = new transaksiReturdtl();

            foreach (DataRow dr in dt.Rows)
            {
                objDtl = new transaksiReturdtl();
                objDtl.Customer_Code = dr[0].ToString().Trim();
                objDtl.Salesman_Code = dr[1].ToString().Trim();
                objDtl.Transaction_Number = dr[2].ToString().Trim();
                objDtl.Transaction_Date = dr[3].ToString().Trim() == "" ? Convert.ToDateTime("1900-01-01") : Helper.FormatDate(dr[3].ToString().Trim(), Helper.Culture.English);
                objDtl.Product_Code = dr[4].ToString().Trim();
                objDtl.Product_Description = dr[5].ToString().Trim();
                objDtl.Product_Index = dr[6].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[6].ToString().Trim());
                objDtl.Selling_Type = dr[7].ToString().Trim();
                objDtl.Product_Quantity = dr[8].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[8].ToString().Trim()); ;
                objDtl.UOM = dr[9].ToString().Trim();
                objDtl.Default_UOM = dr[10].ToString().Trim();
                objDtl.Product_List_Price = dr[11].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[11].ToString().Trim());
                objDtl.UOM_List_Price = dr[12].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[12].ToString().Trim());
                objDtl.Gross_Amount = dr[13].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[13].ToString().Trim());
                objDtl.Product_Discount = dr[14].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[14].ToString().Trim());
                objDtl.Promo_Discount = dr[15].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[15].ToString().Trim());
                objDtl.Sales_Discount = dr[16].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[16].ToString().Trim());
                objDtl.Amount = dr[17].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[17].ToString().Trim());
                objDtl.Tax_Amount = dr[18].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[18].ToString().Trim());
                objDtl.Amount_After_Tax = dr[19].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[19].ToString().Trim());
                objDtl.Customer_Discount_Amount = dr[20].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[20].ToString().Trim());

                listDtl.Add(objDtl);
            }

            transaksiReturdtlDal.SaveUpload(listDtl);
            
            helper.Message = "Data berhasil di Upload !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }
        finally
        {
            recLog log = new recLog();
            log.LogEvent = "Upload CNDetail";
            log.LogMessage = helper.Message;
            log.LogSource = "UploadTransaksiHandler.ashx";
            log.CreatedBy = base.UserLoggedIn;
            log.CreatedDate = DateTime.Now;
            logDal.Save(log);

        }

        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

    }

    private string UploadDNDetail(HttpContext context)
    {
        JSONHelper helper = new JSONHelper();
        string FileName = string.Empty;
        try
        {

            if (context.Request.Files.Count > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0] as HttpPostedFile;

                var file = context.Request.Files[0];

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    string[] files = hpf.FileName.Split(new char[] { '\\' });
                    FileName = files[files.Length - 1];
                }
                else
                {
                    FileName = hpf.FileName;
                }

                byte[] datas = new byte[hpf.ContentLength];
                hpf.InputStream.Position = 0;
                hpf.InputStream.Read(datas, 0, hpf.ContentLength);

                string path = context.Server.MapPath("~/Upload/Transaksi/DNDetail/");
                if (!System.IO.Directory.Exists(path))
                    System.IO.Directory.CreateDirectory(path);


                if (System.IO.File.Exists(path + FileName))
                    System.IO.File.Delete(path + FileName);

                hpf.SaveAs(path + FileName);

                hpf.InputStream.Close();
                hpf.InputStream.Dispose();

            }

            DataTable dt = CSVReader.GetDataTabletFromCSVFile(context.Server.MapPath(@"~/Upload/Transaksi/DNDetail/") + FileName);

            List<transaksiDNdtl> listDtl = new List<transaksiDNdtl>();
            transaksiDNdtl objDtl = new transaksiDNdtl();

            foreach (DataRow dr in dt.Rows)
            {
                objDtl = new transaksiDNdtl();
                objDtl.Customer_Code = dr[0].ToString().Trim();
                objDtl.Salesman_Code = dr[1].ToString().Trim();
                objDtl.Transaction_Number = dr[2].ToString().Trim();
                objDtl.Transaction_Date = dr[3].ToString().Trim() == "" ? Convert.ToDateTime("1900-01-01") : Helper.FormatDate(dr[3].ToString().Trim(), Helper.Culture.English);
                objDtl.Product_Code = dr[4].ToString().Trim();
                objDtl.Product_Description = dr[5].ToString().Trim();
                objDtl.Product_Index = dr[6].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[6].ToString().Trim());
                //objDtl.Selling_Type = dr[7].ToString().Trim();
                objDtl.Product_Quantity = dr[7].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[7].ToString().Trim()); ;
                objDtl.UOM = dr[8].ToString().Trim();
                objDtl.Default_UOM = dr[9].ToString().Trim();
                objDtl.Product_List_Price = dr[10].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[10].ToString().Trim());
                objDtl.UOM_List_Price = dr[11].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[11].ToString().Trim());
                objDtl.Gross_Amount = dr[12].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[12].ToString().Trim());
                objDtl.Net_Amount = dr[13].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[13].ToString().Trim());
                objDtl.Amount_After_Tax = dr[14].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[14].ToString().Trim());
                objDtl.Customer_Discount_Amount = dr[15].ToString().Trim() == "" ? 0 : Convert.ToDouble(dr[15].ToString().Trim());
                objDtl.Reason_Code = dr[16].ToString().Trim();
                objDtl.Reason_Description = dr[17].ToString().Trim();

                listDtl.Add(objDtl);
            }

            transaksiDNdtlDal.SaveUpload(listDtl);
            
            helper.Message = "Data berhasil di Upload !";
            helper.IsSuccess = true;

        }
        catch (Exception ex)
        {

            helper.Message = ex.Message;
            helper.IsSuccess = false;

        }
        finally
        {
            recLog log = new recLog();
            log.LogEvent = "Upload DNDetail";
            log.LogMessage = helper.Message;
            log.LogSource = "UploadTransaksiHandler.ashx";
            log.CreatedBy = base.UserLoggedIn;
            log.CreatedDate = DateTime.Now;
            logDal.Save(log);

        }

        return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

    }
}